package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.oocl.dao.ClientDao;
import com.oocl.factory.DBConFactory;
import com.oocl.pojo.Client;
/**
 * @description: 
 * @author  XIEMI2
 * @date Aug 3, 2017 3:43:20 PM
 * @version 1.0
 */
public class ClientDaoImpl implements ClientDao{

	@Override
	public int saveClient(Client client) {
		String sql = "insert into client(id, uname, password) values(?, ?, ?)";
		Connection con = null;
		PreparedStatement pst = null;
		int m = 0;
		try {
			con = DBConFactory.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, client.getId());
			pst.setString(2, client.getUname());
			pst.setString(3, client.getPassword());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBConFactory.close(con, pst, null);
		}
		return m;
	}

	@Override
	public Client queryByName(String name) {
		String sql = "select * from client where uname = ?";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			con = DBConFactory.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			rs = pst.executeQuery();
			while(rs.next()){
				Client client = new Client(rs.getString("id"), rs.getString("uname"), rs.getString("password"));
				return client;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBConFactory.close(con, pst, rs);
		}
		return null;
	}

	@Override
	public Client validateLogin(String uname, String password) {
		String sql = "select * from client where uname = ? and password = ?";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			con = DBConFactory.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, uname);
			pst.setString(2, password);
			rs = pst.executeQuery();
			while(rs.next()){
				Client client = new Client(rs.getString("id"), rs.getString("uname"), rs.getString("password"));
				return client;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBConFactory.close(con, pst, rs);
		}
		return null;
	}

}


